package com.cdu.ai_intelligent_teaching_and_training_system.controller;

import com.cdu.ai_intelligent_teaching_and_training_system.dto.ApiResponse;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.HttpEntity;

@RestController
@RequestMapping("/ai")
@CrossOrigin(origins = "*")
public class AiController {
    
    @PostMapping("/chat")
    public ResponseEntity<ApiResponse<Map<String, String>>> chat(@RequestBody Map<String, Object> request) {
        try {
            String question = request.get("question") != null ? request.get("question").toString() : 
                             (request.get("text") != null ? request.get("text").toString() : "");
            String subject = request.get("subject") != null ? request.get("subject").toString() : "general";
            
            // 1. 转发到Python FastAPI
            String fastApiUrl = "http://localhost:8000/api/ai/chat";
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            Map<String, Object> payload = new HashMap<>();
            payload.put("question", question);
            payload.put("subject", subject);
            
            // 处理student对象
            Object studentObj = request.get("student");
            if (studentObj instanceof Map) {
                payload.put("student", studentObj);
            }

            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(payload, headers);

            ResponseEntity<Map> response = restTemplate.postForEntity(fastApiUrl, entity, Map.class);
            Map body = response.getBody();
            // FastAPI返回的结构: {success, data:{answer, ...}, ...}
            if (body != null && Boolean.TRUE.equals(body.get("success"))) {
                Map data = (Map) body.get("data");
                Map<String, String> result = new HashMap<>();
                result.put("answer", data.get("answer").toString());
                result.put("question", question);
                return ResponseEntity.ok(ApiResponse.success(result));
            } else {
                return ResponseEntity.ok(ApiResponse.error("AI服务异常"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("AI回答失败：" + e.getMessage()));
        }
    }
    
    @PostMapping("/analyze")
    public ResponseEntity<ApiResponse<Map<String, Object>>> analyzeLearning(@RequestBody Map<String, Object> request) {
        try {
            // 支持多种参数格式
            Long studentId = null;
            Long courseId = null;
            
            if (request.get("studentId") != null) {
                studentId = Long.valueOf(request.get("studentId").toString());
            }
            if (request.get("courseId") != null) {
                courseId = Long.valueOf(request.get("courseId").toString());
            }
            
            // 如果没有提供ID，使用默认值
            if (studentId == null) studentId = 1L;
            if (courseId == null) courseId = 1L;
            // 这里应该进行真实的学习分析，目前返回模拟数据
            Map<String, Object> analysis = generateLearningAnalysis(studentId, courseId);
            
            return ResponseEntity.ok(ApiResponse.success(analysis));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("学习分析失败：" + e.getMessage()));
        }
    }
    
    @PostMapping("/recommend")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getRecommendations(@RequestBody Map<String, Object> request) {
        try {
            Long studentId = Long.valueOf(request.get("studentId").toString());
            
            // 这里应该基于学生的学习情况生成推荐，目前返回模拟数据
            Map<String, Object> recommendations = generateRecommendations(studentId);
            
            return ResponseEntity.ok(ApiResponse.success(recommendations));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取推荐失败：" + e.getMessage()));
        }
    }
    
    private String generateAiResponse(String question, String role) {
        // 模拟AI回答逻辑
        if (question.contains("矩阵")) {
            return "矩阵是线性代数中的重要概念。矩阵乘法遵循特定的规则：两个矩阵A和B的乘积C的第i行第j列元素等于A的第i行与B的第j列对应元素的乘积之和。\n\n推荐学习资源：\n- 线性代数第三章：矩阵运算\n- 矩阵乘法专项练习\n- 矩阵应用实例解析视频";
        } else if (question.contains("微积分")) {
            return "微积分是数学分析的基础，包括微分和积分两个主要部分。微分用于研究函数的变化率，积分用于计算面积和体积。\n\n推荐学习资源：\n- 微积分基础概念\n- 导数计算练习\n- 积分应用实例";
        } else {
            return "我是您的AI学习助手，可以帮您解答数学、物理、计算机科学等学科的问题。请详细描述您的问题，我会尽力为您提供帮助。";
        }
    }
    
    private Map<String, Object> generateLearningAnalysis(Long studentId, Long courseId) {
        Map<String, Object> analysis = new HashMap<>();
        analysis.put("studentId", studentId);
        analysis.put("courseId", courseId);
        analysis.put("progress", 75.5);
        analysis.put("strength", "线性代数");
        analysis.put("weakness", "概率论");
        analysis.put("studyTime", 45.2);
        analysis.put("recommendations", "建议加强概率论的学习，多做相关练习");
        return analysis;
    }
    
    private Map<String, Object> generateRecommendations(Long studentId) {
        Map<String, Object> recommendations = new HashMap<>();
        recommendations.put("studentId", studentId);
        recommendations.put("courses", new String[]{"高等数学精讲,线性代数应用", "概率论与数理统计"});
        recommendations.put("resources", new String[]{"矩阵运算专项练习", "微积分难点解析", "Python数据分析入门"});
        recommendations.put("reason", "基于您的学习进度和成绩表现推荐");
        return recommendations;
    }
} 